package edu.tcc.iot.core.services.impl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;

import edu.tcc.iot.core.services.IConnectionService;
import edu.tcc.iot.utils.Configuration;

public class ConnectionService implements IConnectionService{

	private final static Logger log = Logger.getLogger(ConnectionService.class);
	private ServerSocket serverSocket;

	public ConnectionService() {
		try {
			int port = Integer.parseInt(Configuration.getInstance().getProperty("connection.server.port"));
			log.info("[CERS][ConnectionService] Creating server socket");
			serverSocket = new ServerSocket(port);
			log.info("[CERS][ConnectionService] Server socket created");
		} catch (IOException e) {
			log.error("Error trying to start server");
		}
	}

	public Socket getConnection(){
		log.info("[CERS][ConnectionService] Getting Sockets");
		try {
			log.info("[CERS][ConnectionService] Listening new shelfs");
			Socket socket =  serverSocket.accept();
			log.info("[CERS][ConnectionService] New Shelf found");
			return socket;
		} catch (IOException e) {
			log.error("An error ocurred while watting for connections");
		}
		log.info("[CERS][ConnectionService] No Shelf found, timeout");
		return null;
	}
}
